
'''
-- 用户Token表
CREATE TABLE user_token (
    token_id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL REFERENCES user_info(user_id),
    token VARCHAR(100) NOT NULL,
    expire_time TIMESTAMP NOT NULL
);
'''
import uuid
import psycopg2 
import psycopg2.extras
import datetime

class UserTokenTableMethod:

    def __init__(self, conn, cur):
        
        self.cursor = cur
        self.conn = conn

    def insert_user_token(self, user_id, interval_time=3600*24):
        '''args: user_id, interval_time(default 1 day)'''

        # 生成token
        token = str(uuid.uuid4())
        # 过期时间        
        expire_time = datetime.datetime.now() + datetime.timedelta(seconds=interval_time)
        # 插入数据
        sql = "INSERT INTO user_token (user_id, token, expire_time) VALUES (%s, %s, %s)"
        values = (user_id, token, expire_time)
        self.cursor.execute(sql, values)
        self.conn.commit()
        return token

    def delete_user_token(self, token_id):
        sql = "DELETE FROM user_token WHERE token_id = %s"
        values = (token_id,)
        self.cursor.execute(sql, values)
        self.conn.commit()

    def get_user_token_by_user_id(self, user_id):
        sql = "SELECT * FROM user_token WHERE user_id = %s and expire_time > NOW() ORDER BY token_id DESC"
        self.cursor.execute(sql, (user_id,))
        result = self.cursor.fetchone()
        return result
    
    def delete_user_token_by_user_id(self, user_id):
        sql = "DELETE FROM user_token WHERE user_id = %s"
        values = (user_id,)
        self.cursor.execute(sql, values)
        self.conn.commit()
